﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace TableTop.DataManagement.Addon
{
    [Serializable]
    internal class AddonDomainHelper
        : MarshalByRefObject
    {
        protected Assembly LoadedAssembly
        {
            get;
            set;
        }

        public String AssemblyFullName
        {
            get
            {
                if (this.LoadedAssembly != null)
                    return this.LoadedAssembly.FullName;
                else
                    return string.Empty;
            }
        }

        public IAddonEntryPoint EntryPoint
        {
            get;
            private set;
        }

        public bool IsAddonAssembly(String AssemblyFilename)
        {
            Type[] AssemblyTypes = null;

            if (this.LoadedAssembly != null)
                throw new InvalidOperationException("Assembly already loaded");

            this.LoadedAssembly = Assembly.LoadFile(AssemblyFilename);
            AssemblyTypes = this.LoadedAssembly.GetExportedTypes();

            foreach (Type t in AssemblyTypes)
            {
                Type iaepInterface = null;
                iaepInterface = t.GetInterface(typeof(IAddonEntryPoint).Name);
                if (iaepInterface != null)
                    return true;               
            }
            return false;
        }       

        public void Load(String AssemblyFilename)
        {
            Type[] AssemblyTypes = null;
            this.LoadedAssembly = Assembly.LoadFrom(AssemblyFilename);
            
            AssemblyTypes = this.LoadedAssembly.GetExportedTypes();

            foreach (Type t in AssemblyTypes)
            {
                Type iaepInterface = null;
                iaepInterface = t.GetInterface(typeof(IAddonEntryPoint).Name);
                if (iaepInterface != null)
                {
                    this.EntryPoint = (IAddonEntryPoint)this.LoadedAssembly.CreateInstance(t.FullName);
                    break;
                }                    
            }
        }
    }
}
